package com.leantech.android.browser.ui.favorites

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.CompoundButton.OnCheckedChangeListener
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.cscj.android.repository.db.entity.BrowseHistoryEntity
import com.leantech.android.browser.R
import com.leantech.android.browser.databinding.FragmentHistoryBinding
import com.leantech.android.browser.ui.browser.BrowserActivity
import com.leantech.android.browser.ui.favorites.adapter.BrowserHistoryAdapter
import com.leantech.android.browser.ui.favorites.vm.BrowserHistoryViewModel
import com.leantech.android.browser.ui.favorites.vm.FavoritesViewModel
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.show
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.activityViewModel
import splitties.fragments.start
import splitties.resources.str

class HistoryFragment : Fragment(), BrowserHistoryAdapter.HistoryAdapterCallback {

    private val viewModel by activityViewModel<BrowserHistoryViewModel>()
    private lateinit var binding: FragmentHistoryBinding
    private lateinit var adapter: BrowserHistoryAdapter

    private var listData: List<BrowserHistoryViewModel.HistoryItem>? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentHistoryBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        subscribeFlow()
    }

    private fun initView() {
        binding.editSearch.doOnTextChanged { _, _, _, count ->
            binding.btnCancelSearch.show(count > 0)
            viewModel.searchHistory(binding.editSearch.text?.toString())
        }

        binding.editSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.searchHistory(binding.editSearch.text?.toString())
                true
            } else false
        }

        binding.btnSelectAll.setOnCheckedChangeListener(checkedChangeListener)

        binding.btnCancelSearch.onThrottleClick {
            binding.editSearch.text?.clear()
        }

        binding.btnDelete.onThrottleClick {
            viewModel.deleteHistory()
            viewModel.toggleHistoryEditMode()
        }

        binding.btnDone.onThrottleClick {
            viewModel.toggleHistoryEditMode()
        }

        adapter = BrowserHistoryAdapter(this)
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())

    }

    private val checkedChangeListener = OnCheckedChangeListener { _, isChecked ->
        if (isChecked) {
            selectAll()
        } else {
            viewModel.selectedHistoryIds.clear()
            adapter.selectItems(emptySet())
        }
    }

    private fun selectAll() {
        val allId = viewModel.getAllHistoryId()
        adapter.selectItems(allId)
        viewModel.selectedHistoryIds.addAll(allId)
    }

    private fun subscribeFlow() {
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    //history flow
                    viewModel.historyFlow.collectLatest { historyList ->
                        binding.emptyView.root.show(historyList.isEmpty())
                        adapter.submitList(historyList)
                    }
                }

                launch {
                    viewModel.historyEditMode.collectLatest {
                        val editOn = it == FavoritesViewModel.EditMode.On
                        if (!editOn) {
                            binding.btnSelectAll.isChecked = false
                            viewModel.selectedHistoryIds.clear()
                            updateDeleteButton()
                        }
                        binding.editActionBar.show(editOn)
                        adapter.updateEditMode(editOn)
                    }
                }
            }
        }
    }

    override fun onHistoryItemClick(data: BrowseHistoryEntity, position: Int) {
        requireActivity().finish()
        start<BrowserActivity> {
            action = Intent.ACTION_VIEW
            this.data = Uri.parse(data.url)
        }
    }

    override fun onHistoryItemChecked(data: BrowseHistoryEntity, position: Int, checked: Boolean) {
        if (checked) {
            viewModel.selectedHistoryIds.add(data.id)
        } else {
            viewModel.selectedHistoryIds.remove(data.id)
        }
        adapter.selectItemsNotNotify(viewModel.selectedHistoryIds)

        var size = listData?.size ?: 0
        listData?.forEach {
            if (it is BrowserHistoryViewModel.HistoryItem.Title) {
                size--
            }
        }
        if (viewModel.selectedHistoryIds.size == size) {
            binding.btnSelectAll.setOnCheckedChangeListener(null)
            binding.btnSelectAll.isChecked = true
            binding.btnSelectAll.setOnCheckedChangeListener(checkedChangeListener)
        } else {
            binding.btnSelectAll.setOnCheckedChangeListener(null)
            binding.btnSelectAll.isChecked = false
            binding.btnSelectAll.setOnCheckedChangeListener(checkedChangeListener)
        }

        updateDeleteButton()
        updateSelectAllButton()
    }

    private fun updateDeleteButton() {
        val hasSelectItems = viewModel.selectedHistoryIds.isNotEmpty()
        val text = if (hasSelectItems) "删除(${viewModel.selectedHistoryIds.size})" else str(
            R.string.text_delete
        )
        binding.btnDelete.isSelected = hasSelectItems
        binding.btnDelete.isEnabled = hasSelectItems
        binding.btnDelete.text = text
    }

    private fun updateSelectAllButton() {
        binding.btnSelectAll.setOnCheckedChangeListener(null)
        binding.btnSelectAll.isChecked = viewModel.isAllSelected()
        binding.btnSelectAll.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                selectAll()
            } else {
                viewModel.selectedHistoryIds.clear()
                adapter.selectItems(emptySet())
            }
        }
    }
}